﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

namespace THO7AlgoritmTimerApplication {
    class range : VisionAlgorithm {
        int filter_groote = 0;
        public range(String name) : base(name) { }
        public override Bitmap DoAlgorithm(Bitmap sourceImage) {
            filter_groote = getMarge(); 
            Bitmap returnImage = new Bitmap(sourceImage);
            Rectangle rect = new Rectangle(0, 0, returnImage.Width, returnImage.Height);
            BitmapData myBmpData = returnImage.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
            IntPtr ptr = myBmpData.Scan0;
            int numBytes = returnImage.Width * returnImage.Height * 3;
            byte[] rgbValues = new byte[numBytes];
            byte[] newrgbValues = new byte[numBytes];
            System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, numBytes);

            byte[] median = new byte[filter_groote * filter_groote];
            int positie;

            int regelGroote = returnImage.Width * 3;
            for (int imagex = (filter_groote / 2); imagex < returnImage.Width - (filter_groote / 2); imagex++) {
                for (int imagey = (filter_groote / 2); imagey < returnImage.Height - (filter_groote / 2); imagey++) {
                    int i = 0;
                    for (int y = imagey - (filter_groote / 2); y <= imagey + (filter_groote / 2); y++) {
                        for (int x = imagex - (filter_groote / 2); x <= imagex + (filter_groote / 2); x++) {
                            positie = x * 3 + (y * regelGroote);
                            median[i] = (byte)((rgbValues[positie] + rgbValues[positie + 1] + rgbValues[positie + 2]) / 3);
                            i++;
                        }
                    }
                    Array.Sort(median);
                    byte waarde = (byte)(median[median.Length - 1] - median[0]);
                    newrgbValues[imagex * 3 + (imagey * regelGroote)] = waarde;
                    newrgbValues[imagex * 3 + (imagey * regelGroote) + 1] = waarde;
                    newrgbValues[imagex * 3 + (imagey * regelGroote) + 2] = waarde;
                    Array.Clear(median, 0, median.Length);
                }
            }
            rgbValues = newrgbValues;

            System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, numBytes);
            returnImage.UnlockBits(myBmpData);
            return returnImage;
        }
    }
}
